package com.education.quartz.config;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;

/**
 * @Author: liftsail
 * @Date: 2022/11/22 16:11
 * @Description: 不积跬步无以至千里
 */
@Slf4j
@Configuration
public class QuartzConfigration {

    @Autowired
    private MyJobFactory jobFactory;

    @Bean(name = "SchedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        //factory.setQuartzProperties(quartzProperties());
        factory.setOverwriteExistingJobs(true);
        //延时启动  应用程序 启动 5秒后
        factory.setStartupDelay(1);
        //替换从spring创建实例 使得spring注入 正常运行
        factory.setJobFactory(jobFactory);

        return factory;
    }

    /*@Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        // 在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }*/

    /*
     * quartz初始化监听器
     */
    @Bean
    public QuartzInitializerListener executorListener() {
        return new QuartzInitializerListener();
    }

    /*
     * 通过SchedulerFactoryBean获取Scheduler的实例
     */
    @Bean(name = "Scheduler")
    public Scheduler scheduler() throws IOException {
        ///用于quartz集群,QuartzScheduler 启动时更新己存在的Job，这样就不用每次删除已存在的job记录
        //schedulerFactoryBean().setOverwriteExistingJobs(true);
        //QuartzScheduler 延时启动，应用启动完10秒后 QuartzScheduler 再启动
        //schedulerFactoryBean().setStartupDelay(10);
        schedulerFactoryBean().setAutoStartup(true);
        return schedulerFactoryBean().getScheduler();
    }
}
